package org.apache.rmiloader.kernel;

import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Set;

import org.apache.log4j.Logger;

/**
 * Bound RMI Class to Tomcat RMI Registery
 * @author Joris
 *
 */
public class RmiBounder {

	private Set<Class<?>> rmiList;
	private Logger logger = Logger.getLogger(RmiBounder.class);
	
	public RmiBounder() {
		rmiList = new RmiLookUp().getRmiServices();
	}
	
	public void bound(String host, int port) {
		try {
			Registry registry = LocateRegistry.getRegistry(host, port);
			
			for (Class<?> impl : rmiList) {
				String className = impl.getName();
				String name = className.substring(className.lastIndexOf(".") + 1, className.length());
				Remote stub = (Remote) UnicastRemoteObject.exportObject((Remote)impl.newInstance(), 0);
				registry.rebind(name, stub);
				logger.info(impl.getName() + " recorded in registery with name: " + name);
			}
		} 
		catch (Exception e) {
			throw new RuntimeException(e);		
		}
	}
}
